import services from '@/services/demo';
import { Button, Divider, Form, message,Switch,Row,Col,Input,Upload } from 'antd';
import React, { useRef, useState,useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { FormProps, UploadFile, UploadProps } from 'antd';
import { history } from 'umi';

const { configDetail,updateConfig,insertConfig } =
  services.UserController;

const TableList: React.FC<unknown> = () => {
  const [form] = Form.useForm();
  const [readImageUrl, setReadImageUrl] = useState<string>('');
  const [imageUrl, setImageUrl] = useState<string>('');
  const [readImageUrl2, setReadImageUrl2] = useState<string>('');
  const [imageUrl2, setImageUrl2] = useState<string>('');
  const [actionId,setActionId] = useState<string>('')
  useEffect(()=>{
    configDetail().then((res:any)=>{
      if(res.code=='200'){
        setActionId(res.data.id || '')
        let configJson:any = JSON.parse(res.data.configJson || '{}')
        setReadImageUrl(configJson.imageUrl1)
        setReadImageUrl2(configJson.imageUrl2)
        form.setFieldsValue({...configJson})
      }
    })
  },[])
  const onFinish: FormProps['onFinish'] = (values:any) => {
    console.log('Success:', values);
    let params = {
      id:actionId,
      configJson:JSON.stringify({
        ...values,
        imageUrl1:readImageUrl,
        imageUrl2:readImageUrl2,
      }),
      
    }
    // 新增用
    // insertConfig(params).then((res:any)=>{
    //   if(res.code=='200'){
    //     message.success('修改成功');
    //   }else{
    //     message.error(res.message);
    //   }
    // })
     updateConfig(params).then((res:any)=>{
      if(res.code=='200'){
        message.success('修改成功');
      }else{
        message.error(res.message);
      }
    })
   
  };
  
  const onFinishFailed: FormProps['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
   //上传
   const [loading, setLoading] = useState(false);
   const handleUpload = (e:any) => {
     let file = e.file
     if(file.status=='done'){
       const formData = new FormData();
       formData.append('file', file.originFileObj);
       fetch('/api/sys/upload', {
         method: 'POST',
         body: formData,
       }).then((res) => {
         return res.json()
       })
       .then((res) => {
         console.log(66,res)
         if(res.code=='200'){
           message.success('上传成功');
           let data = JSON.parse(res.data)
           console.log(2,data)
           setReadImageUrl(data.fileReadPath)
           setImageUrl(data.fileUploadPath)
         }else if(res.code=='401'){
           message.error(res.message);
           history.push('/login');
         }else{
           message.error(res.message);
         }
       })
       .catch(() => {
         message.error('upload failed.');
       })
       .finally(() => {
         // setUploading(false);
       });
     }
   };
    //上传
  const handleUpload2 = (e:any) => {
    let file = e.file
    if(file.status=='done'){
      const formData = new FormData();
      formData.append('file', file.originFileObj);
      fetch('/api/sys/upload', {
        method: 'POST',
        body: formData,
      }).then((res) => {
        return res.json()
      })
      .then((res) => {
        console.log(66,res)
        if(res.code=='200'){
          message.success('上传成功');
          let data = JSON.parse(res.data)
          console.log(2,data)
          setReadImageUrl2(data.fileReadPath)
          setImageUrl2(data.fileUploadPath)
        }else if(res.code=='401'){
          message.error(res.message);
          history.push('/login');
        }else{
          message.error(res.message);
        }
      })
      .catch(() => {
        message.error('upload failed.');
      })
      .finally(() => {
        // setUploading(false);
      });
    }
  };
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );
  return (
    <div style={{height:'90vh',backgroundColor:'#fff',padding:'20px'}}>
      <Form
          name="basic"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          style={{ maxWidth: 700 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Row>
            <Col span={24}>
              <Form.Item
                label="姓名"
                name="bankUserName"
              >
                <Input style={{width:'400px'}} />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item
                label="账户"
                name="bankId"
              >
                <Input style={{width:'400px'}} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="所属银行"
                name="bankName"
              >
                <Input style={{width:'400px'}} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="二维码1"
                name="imgUrl1"
              >
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  onChange={handleUpload}
                >
                  {readImageUrl ? <img src={readImageUrl} alt="avatar" style={{ width: '100%',height:'100%' }} /> : uploadButton}
                </Upload>
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="二维码2"
                name="imgUrl2"
              >
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  onChange={handleUpload2}
                >
                  {readImageUrl2 ? <img src={readImageUrl2} alt="avatar" style={{ width: '100%',height:'100%' }} /> : uploadButton}
                </Upload>
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="链接1"
                name="url1"
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="链接2"
                name="url2"
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item wrapperCol={{ offset: 10, span: 16 }}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
    </div>
  );
};

export default TableList;
